import axios, { AxiosResponse, InternalAxiosRequestConfig } from 'axios'
import { Api } from '@/apis/structs.ts'
import { router } from '@/router/router.ts'
import { pinia_global_state } from '@/state/state.ts'

export const api = axios.create({ baseURL: '/api' })
api.interceptors.request.use(async (config:InternalAxiosRequestConfig): Promise<InternalAxiosRequestConfig> => {
  const pinia = pinia_global_state()
  if ('' !== pinia.token) {
    config.headers.setAuthorization('Bearer ' + pinia.token)
  }

  return config
})

api.interceptors.response.use(async (response: AxiosResponse<Api>): Promise<AxiosResponse<Api>> => {
  if (200 != response.status) {
    window.$message.error('请求失败，请稍后再试，详细信息打印在控制台')
    console.log(`请求[${response.request.url}]失败.`, response)
  }

  if (2 === response.data.code) {
    window.$message.info('登录已失效，请重新登录')
    await router.push({ name: 'login', force: true })
    window.location.reload()
  }

  return response
})
